<template>
  <div class="page-container">
    <h2 style="margin-bottom: 20px;">权限管理</h2>
    
    <div class="search-form">
      <t-form :data="searchForm" @submit="handleSearch">
        <t-row :gutter="16">
          <t-col :span="6">
            <t-form-item label="权限名">
              <t-input v-model="searchForm.name" placeholder="请输入权限名" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="权限码">
              <t-input v-model="searchForm.code" placeholder="请输入权限码" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="类型">
              <t-select v-model="searchForm.type" placeholder="请选择类型" clearable>
                <t-option value="1" label="菜单" />
                <t-option value="2" label="按钮" />
                <t-option value="3" label="接口" />
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6" style="display: flex; align-items: flex-end;">
            <t-button theme="primary" type="submit" style="margin-right: 8px;">查询</t-button>
            <t-button variant="outline" @click="handleReset">重置</t-button>
          </t-col>
        </t-row>
      </t-form>
    </div>
    
    <div class="table-actions">
      <t-button theme="primary" @click="showCreateDialog = true">
        <template #icon><t-icon name="add" /></template>
        新增权限
      </t-button>
    </div>
    
    <t-table
      :data="permissionList"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
    >
      <template #type="{ row }">
        <t-tag :theme="getTypeTheme(row.type)" variant="light">
          {{ getTypeText(row.type) }}
        </t-tag>
      </template>
      
      <template #op="{ row }">
        <t-space>
          <t-button variant="text" theme="primary" @click="handleEdit(row)">编辑</t-button>
          <t-popconfirm content="确定删除该权限吗？" @confirm="handleDelete(row.id)">
            <t-button variant="text" theme="danger">删除</t-button>
          </t-popconfirm>
        </t-space>
      </template>
    </t-table>
    
    <!-- 新增/编辑对话框 -->
    <t-dialog
      v-model:visible="showCreateDialog"
      :header="editPermission ? '编辑权限' : '新增权限'"
      width="600px"
      @confirm="handleSubmit"
    >
      <t-form ref="formRef" :data="formData" :rules="rules" label-width="100px">
        <t-form-item label="权限名" name="name">
          <t-input v-model="formData.name" placeholder="请输入权限名" />
        </t-form-item>
        <t-form-item label="权限码" name="code">
          <t-input v-model="formData.code" placeholder="请输入权限码" />
        </t-form-item>
        <t-form-item label="描述" name="description">
          <t-textarea v-model="formData.description" placeholder="请输入权限描述" />
        </t-form-item>
        <t-form-item label="类型" name="type">
          <t-radio-group v-model="formData.type">
            <t-radio value="1">菜单</t-radio>
            <t-radio value="2">按钮</t-radio>
            <t-radio value="3">接口</t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item label="父权限" name="parent_id">
          <t-select v-model="formData.parent_id" placeholder="请选择父权限" clearable>
            <t-option v-for="perm in parentOptions" :key="perm.id" :value="perm.id" :label="perm.name" />
          </t-select>
        </t-form-item>
        <t-form-item label="路径" name="path">
          <t-input v-model="formData.path" placeholder="请输入路径" />
        </t-form-item>
        <t-form-item label="方法" name="method">
          <t-select v-model="formData.method" placeholder="请选择请求方法" clearable>
            <t-option value="GET" label="GET" />
            <t-option value="POST" label="POST" />
            <t-option value="PUT" label="PUT" />
            <t-option value="DELETE" label="DELETE" />
          </t-select>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { permissionAPI } from '@/api/permission'
import type { Permission } from '@/types'

const loading = ref(false)
const permissionList = ref<Permission[]>([])
const parentOptions = ref<Permission[]>([])
const showCreateDialog = ref(false)
const editPermission = ref<Permission | null>(null)

const searchForm = reactive({
  name: '',
  code: '',
  type: ''
})

const formData = reactive({
  name: '',
  code: '',
  description: '',
  type: '1',
  parent_id: 0,
  path: '',
  method: ''
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const columns = [
  { colKey: 'id', title: 'ID', width: 80 },
  { colKey: 'name', title: '权限名' },
  { colKey: 'code', title: '权限码' },
  { colKey: 'description', title: '描述' },
  { colKey: 'type', title: '类型' },
  { colKey: 'path', title: '路径' },
  { colKey: 'method', title: '方法' },
  { colKey: 'created_at', title: '创建时间' },
  { colKey: 'op', title: '操作', width: 120 }
]

const rules = {
  name: [{ required: true, message: '请输入权限名' }],
  code: [{ required: true, message: '请输入权限码' }],
  type: [{ required: true, message: '请选择类型' }]
}

const getTypeText = (type: number) => {
  const types = { 1: '菜单', 2: '按钮', 3: '接口' }
  return types[type as keyof typeof types] || '未知'
}

const getTypeTheme = (type: number) => {
  const themes = { 1: 'success', 2: 'warning', 3: 'primary' }
  return themes[type as keyof typeof themes] || 'default'
}

const loadPermissions = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const response = await permissionAPI.getPermissions(params)
    permissionList.value = response.data
    pagination.total = response.total
  } catch (error) {
    MessagePlugin.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

const loadParentOptions = async () => {
  try {
    const response = await permissionAPI.getPermissions({ page: 1, pageSize: 100 })
    parentOptions.value = response.data.filter(perm => perm.type === 1) // 只显示菜单类型作为父权限
  } catch (error) {
    MessagePlugin.error('获取父权限选项失败')
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadPermissions()
}

const handleReset = () => {
  Object.assign(searchForm, { name: '', code: '', type: '' })
  pagination.current = 1
  loadPermissions()
}

const handlePageChange = (pageInfo: any) => {
  pagination.current = pageInfo.current
  pagination.pageSize = pageInfo.pageSize
  loadPermissions()
}

const handleEdit = (permission: Permission) => {
  editPermission.value = permission
  Object.assign(formData, {
    name: permission.name,
    code: permission.code,
    description: permission.description,
    type: permission.type.toString(),
    parent_id: permission.parent_id,
    path: permission.path,
    method: permission.method
  })
  showCreateDialog.value = true
}

const handleDelete = async (id: number) => {
  try {
    await permissionAPI.deletePermission(id)
    MessagePlugin.success('删除成功')
    loadPermissions()
  } catch (error) {
    MessagePlugin.error('删除失败')
  }
}

const handleSubmit = async () => {
  try {
    const submitData = {
      ...formData,
      type: parseInt(formData.type),
      parent_id: formData.parent_id || 0
    }
    
    if (editPermission.value) {
      await permissionAPI.updatePermission(editPermission.value.id, submitData)
      MessagePlugin.success('更新成功')
    } else {
      await permissionAPI.createPermission(submitData)
      MessagePlugin.success('创建成功')
    }
    showCreateDialog.value = false
    loadPermissions()
  } catch (error) {
    MessagePlugin.error(editPermission.value ? '更新失败' : '创建失败')
  }
}

onMounted(() => {
  loadPermissions()
  loadParentOptions()
})
</script>